package com.hbt.word_provider.service.impl;

import com.hbt.api.entity.*;
import com.hbt.word_provider.dao.FeatureMapper;
import com.hbt.word_provider.dao.WordFeaMapper;
import com.hbt.word_provider.dao.WordMapper;
import com.hbt.word_provider.service.WordService;
import com.hbt.word_provider.utils.MatchStrUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import java.util.List;

@Service
@Transactional
public class WordServiceImpl implements WordService {
    @Autowired
    WordMapper wordMapper;
    @Autowired
    FeatureMapper featureMapper;
    @Autowired
    WordFeaMapper wordFeaMapper;

    public List<Word> getWordByCondition(WordsCondition wordsCondition) {
        System.out.println("service wordcondition:"+wordsCondition);
        return wordMapper.getWordsByCondition(wordsCondition);
    }

    public Word getWordByWordid(int wordid) {
        System.out.println("service wordid:"+wordid);
        return wordMapper.getWordByWordId(wordid);
    }

    public int updateWord(Word word) {
        System.out.println("service word:"+word);
        return wordMapper.updateWord(word);
    }

    public List<Word> findSimilar(String src, int rate, List<Word> words) {
        List<Word> words_result = new LinkedList<Word>();
        for (Word word:words){
            //得出对比率
            int rate_result = MatchStrUtil.matcherStr(src, word.getSrc());
            if (rate_result >= rate){//若对比率达到目标对比率则将单词加入返回集合队列中
                word.setRate(rate_result);
                words_result.add(word);
            }
        }
        return words_result;
    }

    public StaticBean getProgress(int userid) {
        //获得总单词数totalCount
        int total = wordMapper.getTotalCountByUserId(userid);
        //分别获得四个熟练度和四个重要度的count
        int henCmd = wordMapper.getCmdCountByUserIdAndCmdStr(userid, "很熟练")*100/total;
        int cmd = wordMapper.getCmdCountByUserIdAndCmdStr(userid, "熟练")*100/total;
        int noCmd = wordMapper.getCmdCountByUserIdAndCmdStr(userid, "不熟练")*100/total;
        int henImp = wordMapper.getImpCountByUserIdAndImpStr(userid, "很重要")*100/total;
        int imp = wordMapper.getImpCountByUserIdAndImpStr(userid, "重要")*100/total;
        int noImp = wordMapper.getImpCountByUserIdAndImpStr(userid, "不重要")*100/total;

        int cmd_bao = wordMapper.getCmdCountByUserIdAndCmdStr(userid, "保留")*100/total;
        int imp_bao = wordMapper.getImpCountByUserIdAndImpStr(userid, "保留")*100/total;


        StaticBean staticBean = new StaticBean(total, "total");
        staticBean.getStaticBeans().add(new StaticBean(henCmd, "很熟练"));
        staticBean.getStaticBeans().add(new StaticBean(cmd, "熟练"));
        staticBean.getStaticBeans().add(new StaticBean(noCmd, "不熟练"));
        staticBean.getStaticBeans().add(new StaticBean(henImp, "很重要"));
        staticBean.getStaticBeans().add(new StaticBean(imp, "重要"));
        staticBean.getStaticBeans().add(new StaticBean(noImp, "不重要"));

        staticBean.getStaticBeans().add(new StaticBean(cmd_bao, "熟练度保留"));
        staticBean.getStaticBeans().add(new StaticBean(imp_bao, "重要度保留"));
        return staticBean;
    }

    public int delWord(int wordid) {
        int delwordcount = 0;
        int delWFcount = 0;
        //删除word表中的数据
        delwordcount = wordMapper.delWordByWordid(wordid);
        //删除w_f表中含有wordid的数据
        delWFcount = wordFeaMapper.deleteWordFeaByWordid(wordid);
        return delwordcount+delWFcount;
    }

    public boolean hasSameWord(int userid, String src) {
        Word word = wordMapper.getWordByuserIdAndSrc(userid, src);
        if (word != null){
            return true;
        }
        return false;
    }

    public int addWord(Word word){
        wordMapper.insertWord(word);
        //添加特征
        //插入feature
        for (Feature feature : word.getFeatures()) {
            Feature fea = featureMapper.getFeature(feature);
            if (fea == null) {
                featureMapper.insertFeature(feature);
                System.out.println("这是新的feature**********插入feature成功");
                System.out.println("feature插入成功后为：" + feature);
            } else {
                System.out.println("feature是已經存在的：" + fea);
                word.getFeatures().get(word.getFeatures().indexOf(feature)).setId(fea.getId());
            }
        }
        //插入w_f
        for (Feature f : word.getFeatures()) {
            WordFea wordFea = new WordFea();
            wordFea.setWordid(word.getId());
            wordFea.setFeatureid(f.getId());
            wordFeaMapper.insertWordFea(wordFea);
            System.out.println("插入w_f成功");
        }

        return 1;
    }



    public String fanyi(String src) {
        System.out.println("enter fanyi Service impl src:"+src);
        try {
            URL url = new URL("http://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i=" + src);
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection connection = null;
            if (urlConnection instanceof HttpURLConnection) {
                connection = (HttpURLConnection) urlConnection;
            } else {
                System.out.println("请输入 URL 地址");
                return "";
            }
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String urlString = "";
            String current;
            while ((current = in.readLine()) != null) {
                urlString += current;
            }
            JSONObject object = JSONObject.fromString(urlString);
            JSONArray array = (JSONArray) object.getJSONArray("translateResult").get(0);
            JSONObject jsonObject = (JSONObject) array.get(0);
            System.out.println("翻译结果:" + jsonObject.getString("tgt"));
            return jsonObject.getString("tgt");
        } catch (IOException e) {
            e.printStackTrace();
            return "null";
        }
    }


}
